//Francisco "Kiko" Olvera
//loads and plays sounds and music
//sound.h

#include "sound.h"

sound::sound()
{
	m_nextSound = 0;
}

sound::sound(int a_numSounds)
{
	m_nextSound = 0;
	init(a_numSounds);
}

void sound::init(int a_numSounds)
{
	m_maxSounds = a_numSounds;
	System_Create( &fmod ); //Create the main system object.
	fmod->init(100, FMOD_INIT_NORMAL, 0);	// Initialize FMOD system.
	sounds = new FMOD::Sound *[m_maxSounds];
	m_volume = 0.3f;
	soundMuted = false;
}

void sound::Release()
{
	for(int i=0;i<m_nextSound;++i)
	{
		sounds[i]->release();
	}
	delete sounds;
	sounds = 0;//NULL;
	m_nextSound = 0;
	fmod->release();
}

bool sound::loadNextSound(char* name)
{
	if(m_nextSound >= m_maxSounds)
		return false;
	fmod->createSound(name, FMOD_DEFAULT, 0, &sounds[m_nextSound]);
	m_nextSound++;
	return true;
}

void sound::loadMusic(char* name)
{
	fmod->createStream(name, FMOD_LOOP_NORMAL | FMOD_2D | FMOD_HARDWARE, 0, &music);
	hasMusic = true;
}

void sound::playMusic()
{
	fmod->playSound(FMOD_CHANNEL_FREE, music, true, &channel);
	musicPlaying = false;
	channel->setVolume(m_volume);
	toggleMusic();
}

void sound::toggleMusic()
{
	channel->setPaused(musicPlaying);
	musicPlaying = !musicPlaying;
}

bool sound::playSound(int num)
{
	if(soundMuted)
		return false;
	if(num >= m_nextSound)
		return false;
	fmod->playSound(FMOD_CHANNEL_FREE, sounds[num], false, 0);
	return true;
}

void sound::MusicVolumeUp()
{
	float temp = m_volume + 0.01f;
	if(temp <= 1.0f)
		setMusicVolume(temp);
	else
		setMusicVolume(1.0f);
}

void sound::MusicVolumeDown()
{
	float temp = m_volume - 0.01f;
	if(temp >= 0.0f)
		setMusicVolume(temp);
	else
		setMusicVolume(0.0f);
}

void sound::setMusicVolume(float a_volume)
{
	m_volume = a_volume;
	channel->setVolume(m_volume);
}

void sound::toggleMuteSound()
{
	soundMuted = !soundMuted;
}